<?php

namespace App\Console\Commands;

use App\Models\Base\ChatRobot;
use App\Models\Base\ServerList;
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;

class ServerChatRobot extends CommandBase
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'server:chatRobot';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '聊天监控';

    /**
     * Create a new command instance.
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $servers = ServerList::pluck('server_id');
        if ($servers->isEmpty()) {
            return false;
        }
        foreach ($servers as $server_id) {
            setDB($server_id);
            if (false == $this->verifyChat($server_id)) {
                continue;
            }
            echo '统计完成';
        }
    }

    /**
     * 统计聊天广告.
     *
     * @param $server_id
     *
     * @return bool
     */
    protected function verifyChat($server_id)
    {
        $last_time = Carbon::now()->timestamp - 1800;
        $db = DB::reconnect('mysql_game_log');
        $subQuery = $db->table('log_talk')
            ->selectRaw('playerid,COUNT(content) as num,name,content')
            ->where('content', '!=', '')
            ->where('voiceTime', 0)
//            ->where('time','>=',$last_time)
            ->groupBy('playerid')
            ->groupBy('content');
        $result = $db->table(DB::raw("({$subQuery->toSql()}) as a"))
            ->mergeBindings($subQuery)
            ->where('a.num', '>', 2)
            ->get();
        if ($result->isEmpty()) {
            return false;
        }
        foreach ($result as $val) {
            $model = new ChatRobot();
            $model->server_id = $server_id;
            $model->player_id = $val->playerid;
            $model->name = $val->name;
            $model->content = $val->content;
            $model->number = $val->num;
            $model->save();
        }

        return true;
    }
}
